/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cn2;

import java.net.*;
import java.io.*;

/**
 *
 * @author michaellangmayr
 */
public class ListenerThread extends Thread {
    private ServerSocket ss;
    private int port = 0;
    private boolean run = true;
    private Overlay myOverlay = null;

    public ListenerThread(int port, Overlay o) {
        this.port = port;
        this.myOverlay = o;
    }

    private void startListening() throws Exception {
        System.out.println("[Listener] Listening on port " + this.port + "...");
        this.ss = new ServerSocket(this.port);
        while(run) {
            Socket clientSocket = ss.accept();
            this.myOverlay.setLocalAddress(clientSocket.getLocalAddress().getHostAddress());
            System.out.println("[Listener] Incoming peer connection from: " + clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort());
            ClientHandlerThread clientHandler = new ClientHandlerThread(clientSocket, this.myOverlay);
            clientHandler.start();

        }

        this.ss.close();        
    }

    @Override
    public void run() {
        try {
            this.startListening();
        } catch (Exception e) {
            System.out.println("[Listener] exception " + e.toString());
        }
    }   

}
